<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script src="https://cdn.bootcdn.net/ajax/libs/mqtt/4.1.0/mqtt.min.js"></script>


  <script>
    const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)

    const host = 'ws://192.168.108.226:8083/mqtt'

    const options = {
      keepalive: 60,
      clientId: clientId,
      username: 'mica',
      password: 'mica',
      protocolId: 'MQTT',
      protocolVersion: 4,
      clean: true,
      reconnectPeriod: 1000,
      connectTimeout: 30 * 1000,
      will: {
        topic: 'WillMsg',
        payload: 'Connection Closed abnormally..!',
        qos: 0,
        retain: false
      },
    }

    console.log('Connecting mqtt client')
    const client = mqtt.connect(host, options)

    client.on('error', (err) => {
      console.log('Connection error: ', err)
      client.end()
    })

    client.on('reconnect', () => {
      console.log('Reconnecting...')
    })

    // 成功连接后触发的回调
    client.on('connect', () => {
      console.log('已经连接成功');
      // 订阅主题，这里可以订阅多个主题
      client.subscribe(["/front/heartRate/1"], () => {
         console.log(`订阅了主题`)
      })
    });

    // 当客户端收到一个发布过来的消息时触发回调
    /**
     * topic：收到的报文的topic
     * message：收到的数据包的负载playload
     * packet：MQTT 报文信息，其中包含 QoS、retain 等信息
     */
    client.on('message', function (topic, message, packet) {
      // 这里有可能拿到的数据格式是Uint8Array格式，可以直接用toString转成字符串
      // let data = JSON.parse(message.toString());
      console.log("获取到的数据：", message)
      console.log("数据对应订阅主题：", topic)
      console.log("获取到的数据包：", packet)
      const jsonString = new TextDecoder().decode(message);

// 将字符串解析为JSON对象
      const jsonObject = JSON.parse(jsonString);
      console.log(jsonObject)
    });
  </script>
</body>
</html>
